package com.xiaoshuidi.cloud.module.member.xxljob;

import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.contract.api.ContractApi;
import com.xiaoshuidi.cloud.module.member.enums.point.PointRecordEnums;
import com.xiaoshuidi.cloud.module.member.pojo.user.MemberUser;
import com.xiaoshuidi.cloud.module.member.service.point.MemberPointsService;
import com.xiaoshuidi.cloud.module.member.service.user.MemberUserService;
import com.xiaoshuidi.cloud.module.member.util.CustomDateUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class MemberBirthdaySendPointsJob {
    private final MemberUserService memberUserService;
    private final MemberPointsService memberPointsService;

    private final ContractApi contractApi;


    @TenantIgnore
    @XxlJob("member-birthday-send-points-job")
    @Transactional
    public void execute() {
        //从数据中获取生日不为空的会员
        List<MemberUser> users = memberUserService.getBirthDayUser();
        List<MemberUser> list = new ArrayList<>();
        if (users != null && users.size() > 0) {
            for (MemberUser user : users) {
                boolean flag = CustomDateUtil.todayIsBirthday(user.getBirthday());
                if (flag) {
                    list.add(user);
                }
            }
        }
        //发送积分
        if (list != null && list.size() > 0) {
            for (MemberUser u : list) {
                //生日当天发放2000积分
                log.info("用户{}生日赠送积分2000", JsonUtils.toJsonString(u));
                TenantUtils.execute(u.getTenantId(),()->{
                    try {
                        CommonResult<Boolean> status = contractApi.getPersonContractRoomStatus(u.getId());
                        if(status.isSuccess()&&status.getData()){
                            memberPointsService.memberPointsChange(u.getId(), 2000, PointRecordEnums.BIRTHDAY_GIFT, "租客生日当天发放2000积分");
                        }
                    } catch (Exception e) {
                        log.error("获取用户是否是在租用户失败,{}",e.getMessage());
                    }
                });
            }
        }

    }

}
